from plot import Plot
from pygame import Surface
import math

plot_size = 40

# Holds a collection of Plots.
# A Plot is referenced by column and row number, starting at 0.
# Because this object caches its images, self.changed must be set to True if the contents of the Field change to update the image.
class Field:
    def __init__(self, columns, rows):
        self.columns = columns
        self.rows = rows        
        self.plots = [[Plot(0) for j in range(rows)] for i in range(columns)]
        
        self.changed = True
        self.image = None
    
    # find the plant at the specified column and row
    def get_plant(self, column, row):
        return self.get(column, row).get_plant()
    
    # find the plant at the plot nearest to the specified point
    def get_plant(self, (x, y)):
        return self.get_plant(coord_to_index(x), coord_to_index(y))
    
    # set a plant at the plot nearest to the specified point; return true if set
    def set_plant(self, (x, y), plant):
        self.changed = True
        return self.get(self.coord_to_index(x), self.coord_to_index(y)).set_plant(plant)
    
    def set_watered(self, (x, y)):
        self.get(self.coord_to_index(x), self.coord_to_index(y)).set_watered()
        self.changed = True
    
    # called whenever the game's turn is ended
    def end_turn(self):
        for i in range(self.columns): 
            for j in range(self.rows):
                self.get(i, j).inc_age()
        self.changed = True
    
    # given an coordinate, change it into an index on this field
    def coord_to_index(self, i):
        return int(math.ceil(i / plot_size))
        
    def interact(self, game):
        #find which plot the player is on
        coords = game.map.get_item(self).get_relative_position(game.player.get_front())
        plot = self.get(self.coord_to_index(coords[0]), self.coord_to_index(coords[1]))
        game.player.add_money(plot.harvest())
        self.changed = True
    
    #return the plot at (column, row)
    def get(self, column, row):
        if column >= self.columns:
            column = self.columns
        if row >= self.rows:
            row = self.rows
        return self.plots[column][row]
    
    def walkable(self):
        return True
    
    def get_image(self):
        if self.changed:
            self.image = Surface((plot_size * self.columns, plot_size * self.rows))
            for i in range(self.columns):
                for j in range(self.rows):
                    self.image.blit(self.get(i, j).get_tile(), (plot_size * i, plot_size * j))
            self.changed = False
        return self.image